package com.dongdongshop.controller;

import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import com.dongdongsop.data.AjaxResult;
import com.dongdongsop.em.ResultEnum;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckill")
public class SeckillController {

    @DubboReference
    private SeckillService seckillService;


    //缓存预热：将数据提前放入缓存中
    @RequestMapping("catchPrHot")
    @ResponseBody
    public String catchPrHot(){
        seckillService.catchPrHot();
        return "OK";
    }

    //查询秒杀商品列表
    @RequestMapping("findSeckillList")
    public String findSeckillList(Model model){
        List<TbSeckillGoods> goodsList = seckillService.findSeckillList();
        model.addAttribute("goodsList",goodsList);
        return "seckill-index";
    }

    @RequestMapping("findSeckillById")
    public String findSeckillById(Long id,Model model){
        TbSeckillGoods seckillGoods = seckillService.findSeckillById(id);
        model.addAttribute("goods",seckillGoods);
        return "seckill-item";
    }

    @RequestMapping("createOrder")
    @ResponseBody
    public AjaxResult createOrder(Long id) throws Exception{
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return AjaxResult.R(ResultEnum.NO_LOGIN);
        }
        try {
            seckillService.createOrder(id,user.getUsername());
            return AjaxResult.OK();
        }catch (Exception e){
            return AjaxResult.R(ResultEnum.SALEOVER);
        }
    }

    //获取订单的ID
    @RequestMapping("getOrder")
    @ResponseBody
    public AjaxResult getOrder(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        Long orderId = seckillService.getOrderIdByUserName(user.getUsername());
        if (orderId != null){
            return AjaxResult.OK().setData(orderId);
        }
        return AjaxResult.ERROR();
    }
}
